<template>
    <div class="box-content">
        <div class="navigation">订单管理/订单列表</div>
        <!--搜索-->
        <div class="mt-3">
            <div>
                <el-date-picker
                        class=" mrt-10"
                        style="width: 350px;"
                        v-model="searchParams.uploadDate"
                        type="datetimerange"
                        range-separator="~"
                        value-format="yyyy-MM-dd HH:mm:ss"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期">
                </el-date-picker>
                <user-search class=" mrt-10" @changeName="changeName"></user-search>
                <el-input
                        class="mrt-10"
                        style="width: 100px;"
                        placeholder="订单号"
                        v-model="searchParams.orderNum"
                        clearable>
                </el-input>
                <el-select v-model="searchParams.orderStatus" placeholder="订单状态" :clearable="true" style="width:120px;" class="mrt-10">
                    <el-option label="未审核" value="0"></el-option>
                    <el-option label="已审核" value="1"></el-option>
                    <el-option label="已拒绝" value="2"></el-option>
                    <el-option label="用户取消" value="-1"></el-option>
                    <el-option label="管理员取消" value="-2"></el-option>
                </el-select>
                <el-select v-model="searchParams.isShiYong" placeholder="是否试用" :clearable="true" style="width:120px;" class="mrt-10">
                    <el-option label="是" value="1">是</el-option>
                    <el-option label="否" value="0">否</el-option>
                </el-select>


                <el-button type="primary" @click="onSearch">查询</el-button>
            </div>
        </div>
        <!--表格-->
        <div class="mt-3">
            <el-table
                    :data="fileData"
                    v-loading="loading"
                    align="center"
                    :element-loading-text="loadText"
                    :header-cell-style="tableHeaderColor"
                    stripe
                    style="width: 100%">
                <el-table-column
                        prop="id"
                        label="订单号"
                        align="center"
                        width="80">
                </el-table-column>
                <el-table-column
                        prop="user.name"
                        label="商户名"
                        align="center">
                </el-table-column>
                <el-table-column
                        label="订单条件"
                width="200">
                    <template slot-scope="scope">
                        <div>行业: {{scope.row.type?scope.row.type.type:'无'}}</div>
                        <div>地区: {{scope.row.place}}</div>
                    </template>
                </el-table-column>
                <el-table-column
                        label="条数"
                        width="200">
                    <template slot-scope="scope">
                        <div>订单条数：{{scope.row.days * scope.row.number}}</div>
                        <div>累计上传：{{scope.row.all_send}}</div>
                    </template>
                </el-table-column>
                <el-table-column
                        label="试用"
                        width="50">
                    <template slot-scope="scope">
                        <div>{{scope.row.can_free?'是':'否'}}</div>
                    </template>
                </el-table-column>
                <el-table-column
                        label="当日已上传(条)"
                        align="center"
                        width="120">
                    <template slot-scope="scope">
                        <div>{{scope.row.today_send}}</div>
                    </template>
                </el-table-column>
                <el-table-column
                        label="当日应上传(条)"
                        align="center"
                        width="120">
                    <template slot-scope="scope">
                        <div>{{scope.row.number}}</div>
                    </template>
                </el-table-column>
                <el-table-column
                        label="下单日期"
                        align="center"
                        width="140">
                    <template slot-scope="scope">
                        <div align="center">{{scope.row['created_at']?scope.row['created_at'].slice(0, 11):'无'}}</div>
                        <div align="center">{{scope.row['created_at']?scope.row['created_at'].slice(11 ):'无'}}</div>
                    </template>
                </el-table-column>
                <el-table-column
                        label="订单状态"
                        width="80">
                    <template slot-scope="scope">
                        <el-button
                                size="mini"
                                type="default"
                                @click="toExamine(scope.row)" v-if="scope.row.status == 0">审核
                        </el-button>
                        <div v-else>{{scope.row.status_link}}</div>
                    </template>
                </el-table-column>
                <el-table-column
                        label="完成状态"
                        fixed="right"
                        align="center"
                        width="100">
                    <template slot-scope="scope">
                        <div v-if="scope.row.all_send >= (scope.row.days * scope.row.number)">已完成</div>
                        <div v-else>
                            <el-button
                                    size="mini"
                                    type="primary"
                                    icon="el-icon-upload2"
                                    @click="importQuato(scope.row)" v-if="scope.row.status == 1 && scope.row.all_send < (scope.row.days * scope.row.number)">导入
                            </el-button>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column
                        label="操作"
                        fixed="right"
                        align="center"
                        width="80"
                >
                    <template slot-scope="scope">
                        <el-button
                                size="mini"
                                type="danger"
                                @click="handleDelete(scope.row)">删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="mt-3 float-right">
                <el-pagination
                        background
                        @size-change="handleSizeChange"
                        @current-change="handleCurrentChange"
                        :current-page="pageInfo.current_page"
                        :page-size="pageInfo.per_page"
                        layout="total, sizes, prev, pager, next, jumper"
                        :total="pageInfo.total">
                </el-pagination>
            </div>
        </div>
        <el-dialog
                :title="dialog.title"
                :visible.sync="dialog.dialogUpload"
                :close-on-click-modal="false"
                width="500px"
        >
            <div style="text-align: center" v-loading="loadingUpload" element-loading-text="文件上传中，请勿关闭">
                <el-upload
                        class="upload-demo"
                        drag
                        action="123"
                        :before-upload="beforeAvatarUpload"
                        :onError="uploadError"
                        :onSuccess="uploadSuccess">
                    <i class="el-icon-upload"></i>
                    <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                    <div class="el-upload__tip" slot="tip">只能上传xls、xlsx文件</div>
                    <!--<div class="progress" @click="beforeAvatarUpload" :style="{backgroundImage:'linear-gradient(to right,#C0C7CB 0%,#C0C7CB '+progress+',#E1E6E9 '+progress+',#E1E6E9 100%)'}"></div>-->
                </el-upload>
            </div>

            <div slot="footer" class="dialog-footer">
                <el-button v-on:click="dialog.dialogUpload = false">取 消</el-button>
                <el-button type="primary" v-on:click="dialog.dialogUpload = false">确 定</el-button>
            </div>
        </el-dialog>　　
    </div>
</template>

<script>
    import axios from 'axios';
    import UserSearch from '../../components/UserInfo.vue'
    export default {
        name: "BoxList",
        components:{
            UserSearch
        },
        data() {
            return {
                progress: null,
                searchStr:'',
                searchParams: {
                    merchantName: '',
                    orderNum: '',
                    uploadName: '',
                    isShiYong: '',
                    orderStatus: '',
                    uploadDate: []
                },
                loading: false,
                loadingUpload: false,
                loadText: '数据加载中',
                pageInfo: {
                    per_page: 10,
                    total: 0,
                    current_page: 1,
                },
                fileData: [],
                dialog: {
                    title: '数据导入',
                    dialogUpload: false
                },

            }
        },
        created() {
            this.getOrderList();
        },
        methods: {
            changeName(val) {
                this.searchParams.merchantName = val;
            },
            onSearch() {
                this.searchStr = "";
                if (this.searchParams.merchantName) {
                    this.addConStr();
                    this.searchStr += `user_id=${this.searchParams.merchantName}`;
                }
                if (this.searchParams.orderStatus) {
                    this.addConStr();
                    this.searchStr += `status=${this.searchParams.orderStatus}`;
                }
                if (this.searchParams.orderNum) {
                    this.addConStr();
                    this.searchStr += `id=${this.searchParams.orderNum}`;
                }
                if (this.searchParams.isShiYong) {
                    this.addConStr();
                    this.searchStr += `can_free=${this.searchParams.isShiYong}`;
                }
                if (this.searchParams.uploadDate && this.searchParams.uploadDate.length > 0) {
                    this.addConStr();
                    this.searchStr+=`created_at$=>=${this.searchParams.uploadDate[0]},<=${this.searchParams.uploadDate[1]}`;
                }
                this.pageInfo.current_page = 1;
                this.getOrderList();
            },
            addConStr() {
                if (this.searchStr.length > 0) {
                    this.searchStr += '&';
                } else {
                    this.searchStr += '?';
                }
            },
            toExamine(val){
                this.$confirm('确定审核此订单, 是否继续?', '提示', {
                    distinguishCancelAndClose: true,
                    confirmButtonText: '同意',
                    cancelButtonText: '拒绝',
                    type: 'warning'
                }).then(() => {
                    this.shenHe(val,1);
                }).catch((action) => {
                    if (action === 'cancel') {
                        this.shenHe(val,2);
                    }
                });

            }, // 审核
            shenHe(val,status) {
                this.$http.put('api/admin/common/apply/' + val.id, {status: status})
                    .then((result) => {
                        this.$message({
                            type: 'success',
                            message: '审核成功!',
                            during:1000
                        });
                        this.getOrderList();
                    })
                    .catch((err) => {
                        this.$message.warning(err.data.msg || "数据异常，请重试");
                    })
            },
            importQuato(val) {  // 上传文件
                this.selectOrderId = val.id;
                this.dialog.dialogUpload = true;
            },
            beforeAvatarUpload (file) {
                console.info('file',file);
                var fileName=new Array()
                fileName =file.name.split('.');
                const extension = fileName[fileName.length-1] === 'xls'
                const extension2 =  fileName[fileName.length-1]=== 'xlsx'
                if (!extension && !extension2) {
                    this.$message({
                        message: '上传模板只能是xls、xlsx格式!',
                        type: 'warning'
                    });
                }
                if (extension || extension2) {
                    let fd = new FormData()
                    fd.append('applyId', this.selectOrderId)
                    fd.append('fileUpload', file)
                    this.newImport(fd);
                }
                return false;
            },
            //提示信息
            uploadSuccess (response) {
                let code = response.returncode;
                let msg = response.msg;
                this.open(msg, code);
            },
            // 上传错误
            uploadError (response) {
                this.open("500", "文件导入异常！");
            },
            open: function (msg, code) {
                if (code == '000') {
                    this.$alert(msg, '提示', {
                        confirmButtonText: '确定',
                        type: 'success',
                        callback: action => {
                            this.dialog.dialogUpload = false;
                            // location.reload();
                        }
                    });
                } else {
                    this.$alert(msg, '提示', {
                        confirmButtonText: '确定',
                        type: 'error',
                        callback: action => {
                            this.dialog.dialogUpload = false;
                            // location.reload();
                        }
                    });
                }
            },
            newImport (data) {
                let config = {
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                        'Authorization' : 'Bearer' + localStorage.getItem('token')
                    }
                };
                this.loadingUpload = true;
                axios.post(process.env.VUE_APP_API_HOST + 'api/admin/common/uploadInfo', data,config)
                    .then((res) => {
                        this.$message({
                            type: 'success',
                            message: res.data.msg,
                            during:1000
                        });
                        this.loadingUpload = false;
                        this.dialog.dialogUpload = false;
                        this.onSearch();
                    })
                    .catch((err) => {
                        this.loadingUpload = false;
                        this.$message.warning(err.response.data.msg || "数据异常，请重试");
                    })
            },
            getOrderList() {
                this.loading = true;
                this.$http.get('api/admin/common/apply' + this.searchStr, {
                    params: {
                        pageSize: this.pageInfo.per_page,
                        page: this.pageInfo.current_page
                    }
                })
                    .then((result) => {
                        this.fileData = result.data;
                        this.pageInfo.total = result.meta.total;
                        this.loading = false;
                    })
                    .catch((err) => {
                        this.loading = false;
                        this.$message.warning(err.data.msg || "数据异常，请重试");
                    })
            },
            submitCostomer(formName) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                    } else {
                        console.log('error submit!!');
                        return false;
                    }
                });
            },
            handleDelete(val) {
                this.$confirm('此操作将永久删除此订单, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.$http.delete('api/admin/common/apply/' + val.id)
                        .then((result) => {
                            this.$message({
                                type: 'success',
                                message: '删除成功!',
                                during:1000
                            });
                            this.getOrderList();
                        })
                        .catch((err) => {
                            this.$message.warning(err.data.msg || "数据异常，请重试");
                        })
                }).catch(() => {
                });
            },
            handleSizeChange(val) {
                this.pageInfo.current_page = 1;
                this.pageInfo.per_page = val;
                this.getOrderList();
            },
            handleCurrentChange(val) {
                this.pageInfo.current_page = val;
                this.getOrderList();
            },
            tableHeaderColor({row, column, rowIndex, columnIndex}) {
                if (rowIndex === 0) {
                    return 'background-color: #FAFAFA;color: #000;font-weight: 500;height:54px;font-size:14px'
                }
            }
        }
    }
</script>

<style scoped>
    .shen-he{
        padding-right: 10px;
    }
    .shen-he:hover{
        cursor: pointer;
        color:#409EFF;
        text-decoration: underline;
    }
</style>